package server;

import java.util.Collections;
import java.util.List;
import java.util.Vector;

import shared.PlayerPosition;

import deck.Card;
import deck.Suit;
import deck.Value;

public class UtilScoring {

	public static Card determineHigh(List<Card> playedCards, Suit trump) {
		List<Card> trumpCards = getSortedTrumpCards(playedCards, trump);
		return trumpCards.get(trumpCards.size());
	}
	public static Card determineLow(List<Card> playedCards, Suit trump) {
		List<Card> trumpCards = getSortedTrumpCards(playedCards, trump);
		return trumpCards.get(0);
	}
	public static Card determineJack(List<Card> playedCards, Suit trump) {
		List<Card> trumpCards = getSortedTrumpCards(playedCards, trump);
		for (Card c : trumpCards) {
			if (c.getValue() == Value.JACK) {
				return c;
			}
		}
		return null;
	}
	
	// returns north if north/south wins, and east if east/west wins.  If both the same, null is returned
	public static PlayerPosition determineGame(List<Card> northSouth, List<Card> eastWest) {
		List<Card> nsGame = getGameCards(northSouth);
		List<Card> ewGame = getGameCards(eastWest);
		
		int nsScore = getScore(nsGame);
		int ewScore = getScore(ewGame);
		
		if (nsScore > ewScore) {
			return PlayerPosition.NORTH;
		}
		else if (ewScore > nsScore) {
			return PlayerPosition.EAST;
		} 
		else {
			return null;
		}
				
	}
	
	private static int getScore(List<Card> gameCards) {
		int score = 0;
		for (Card c : gameCards) {
			switch (c.getValue()) {
			case TEN: score += 10; break;
			case JACK: score += 1; break;
			case QUEEN: score += 2; break;
			case KING: score += 3; break;
			case ACE: score += 4; break;
			}
		}
		return score;
	}
	
	private static List<Card> getGameCards(List<Card> cards) {
		List<Card> gameCards = new Vector<Card>();
		for (Card c : cards) {
			if (c.getValue() == Value.TEN || 
				c.getValue() == Value.JACK || 
				c.getValue() == Value.QUEEN || 
				c.getValue() == Value.KING || 
				c.getValue() == Value.ACE) {
				
				gameCards.add(c);
				
			}
		}
		return gameCards;
	}
	
	private static List<Card> getSortedTrumpCards(List<Card> playedCards, Suit trump) {
		List<Card> trumpCards = new Vector<Card>();
		for (Card c : playedCards) {
			if (c.getSuit() == trump) {
				trumpCards.add(c);
			}
		}
		Collections.sort(trumpCards);
		return trumpCards;
	}
}
